import { useRequest } from "@/hooks/use-request";
import { antdUtils } from "@/utils/antd";
import { useMount } from "ahooks";
import { DatePicker, Form, Input, Modal, Select } from "antd";
import dayjs from "dayjs";
import React, { useEffect, useState } from "react";
import projectService, { ProjectBean } from "./service";

interface CreateProjectProps {
  visible: boolean;
  onCancel: (flag?: boolean) => void;
  curRecord?: ProjectBean | null;
  onSave: () => void;
  editData?: ProjectBean | null;
}

const NewAndEditProject: React.FC<CreateProjectProps> = (props) => {
  const { visible, onCancel, onSave, editData } = props;
  const [form] = Form.useForm();
  const [saveLoading, setSaveLoading] = useState(false);
  const [allUsers, setAllUsers] = useState<any[]>([]);
  const { runAsync: getAllUser } = useRequest(projectService.getAllUser, {
    manual: true,
  });

  useEffect(() => {
    if (visible) {
      setInitValue();
    } else {
      form.resetFields();
    }
  }, [visible]);

  useMount(async () => {
    const [error, data] = await getAllUser();
    if (!error) {
      const list = data.map((user: any) => {
        return {
          value: user.id,
          label: user.nickName,
        };
      });
      setAllUsers(list);
    }
  });

  async function setInitValue() {
    if (editData) {
      const a: any = { ...editData };
      a.startTime = dayjs(editData.startTime);
      a.endTime = dayjs(editData.endTime);
      a.users = a.users.map((e: any) => {
        return e.id;
      });

      form.setFieldsValue(a);
    }
  }

  const save = async (values: any) => {
    setSaveLoading(true);
    values.startTime = dayjs(values.startTime).format("YYYY-MM-DD");
    values.endTime = dayjs(values.endTime).format("YYYY-MM-DD");
    const b = values.users.map((e: any) => {
      const a = allUsers.filter((ee: any) => e === ee.value);
      return { id: e, nickName: a[0].label };
    });
    values.users = b;
    if (editData) {
      values.id = editData.id;
      const [error] = await projectService.upDateProject(values);
      if (!error) {
        antdUtils.message?.success("新增成功");
        onSave();
      }
    } else {
      const [error] = await projectService.addProject(values);
      if (!error) {
        antdUtils.message?.success("新增成功");
        onSave();
      }
    }
    setSaveLoading(false);
  };

  return (
    <Modal
      open={visible}
      title={editData ? `编辑 ${editData!.name}` : "新建"}
      onOk={() => {
        form.submit();
      }}
      confirmLoading={saveLoading}
      width={640}
      onCancel={() => {
        onCancel();
      }}
      afterClose={() => {
        form.resetFields();
        setSaveLoading(false);
      }}
      destroyOnClose
    >
      <Form
        form={form}
        onFinish={save}
        labelCol={{ flex: "0 0 100px" }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item
          label="名称"
          name="name"
          rules={[
            {
              required: true,
              message: "请输入项目名称",
            },
          ]}
        >
          <Input placeholder="请输入项目名称" />
        </Form.Item>
        <Form.Item label="编号" name="number">
          <Input placeholder="请输入项目编号" />
        </Form.Item>
        <Form.Item label="描述" name="describe">
          <Input.TextArea placeholder="请输入项目描述" />
        </Form.Item>
        <Form.Item label="备注" name="notes">
          <Input.TextArea placeholder="请输入备注" />
        </Form.Item>
        <Form.Item label="关联人员" name="users">
          <Select
            mode="multiple"
            size="large"
            placeholder="关联人员"
            style={{ width: "100%" }}
            options={allUsers}
          />
        </Form.Item>
        <Form.Item
          label="开始时间"
          name="startTime"
          rules={[
            {
              required: true,
              message: "请输入项目名称",
            },
          ]}
        >
          <DatePicker format="YYYY-MM-DD" />
        </Form.Item>
        <Form.Item
          label="结束时间"
          name="endTime"
          rules={[
            {
              required: true,
              message: "请输入项目名称",
            },
          ]}
        >
          <DatePicker format="YYYY-MM-DD" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default NewAndEditProject;
